<template>
  <div>
    <el-dialog title="分配权限" :visible="visible" @close="cancel">
      <el-tree
        ref="tree"
        :data="data"
        :default-checked-keys="defaultData"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        check-strictly
        default-expand-all
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitPermission">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionListRequest, assignRolesRequest } from '@/api/permission'
import { transformListTotree } from '@/utils'
import { getRoleDetailRequest } from '@/api/employee'
export default {
  name: 'PermissonTree',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      defaultData: [],
      currentId: null
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取默认的树形数据
    async getPermissionList() {
      const res = await getPermissionListRequest()
      // 平铺数据转换为tree树形数据--- 带有children
      this.data = transformListTotree(res.data, 0)
    },
    // 获取默认值,由父组件调用,并将id存储用于提交请求
    async getRoleDetail(id) {
      this.currentId = id
      const res2 = await getRoleDetailRequest(id)
      this.defaultData = res2.data.permIds
      console.log(this.defaultData)
    },
    // 清除默认数据并关闭
    cancel() {
      this.$refs.tree.setCheckedKeys([])
      this.$emit('update:visible', false)
    },
    // 提交更新权限
    async submitPermission() {
      const arr = this.$refs.tree.getCheckedKeys()
      const res = await assignRolesRequest({
        id: this.currentId,
        permIds: arr
      })
      this.$message.success(res.message)
      this.cancel()
    }
  }
}
</script>
<style lang='scss'  scoped>
</style>
